package ebook.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.nio.channels.Channels;

import com.adobe.dp.epub.io.OCFContainerWriter;
import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.files.AppEngineFile;
import com.google.appengine.api.files.FileReadChannel;
import com.google.appengine.api.files.FileService;
import com.google.appengine.api.files.FileServiceFactory;
import com.google.appengine.api.files.FileWriteChannel;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

import ebook.client.EpubService;
import ebook.shared.FieldVerifier;

@SuppressWarnings({ "serial", "deprecation" })
public class EpubServiceImpl extends RemoteServiceServlet implements EpubService {
	public String greetServer(String Title, String Chap, String ContentOfChap) throws IllegalArgumentException {
		// Verify that the input is valid.
		if (!FieldVerifier.isValidName(Title, Chap, ContentOfChap)) {
			// If the input is not valid, throw an IllegalArgumentException back to the client.
			throw new IllegalArgumentException(
					"Name must be at least 4 characters long");
		}

		// Escape data from the client to avoid cross-site script
		// vulnerabilities.
		Title = escapeHtml(Title);
		Chap = escapeHtml(Chap);
		
////read content from url
//		URL tangthuvien;
//		try {
//			tangthuvien = new URL(ContentOfChap);
//			URLConnection ttv = tangthuvien.openConnection();
//	        BufferedReader in = new BufferedReader(new InputStreamReader(ttv.getInputStream(),"UTF8"));
//	        ContentOfChap = "";
//	        String tmp = "";
//	        String inputLine;
//			while ((inputLine = in.readLine()) != null) {
//				if(inputLine.toLowerCase().contains("<!-- message -->".toLowerCase())) {
//					tmp = "";
//				}
//				if(inputLine.toLowerCase().contains("this.value = 'Hide';".toLowerCase())) {
//					ContentOfChap = ContentOfChap + tmp;
//				}
//				tmp = tmp + inputLine;
//			}
//			System.out.println(tmp);
//			System.out.println(ContentOfChap);
//			in.close();
//		} catch (IOException e1) {
//			// TODO Auto-generated catch block
//			e1.printStackTrace();
//		}
//        
////end read content from url

		// CREATE A NEW EPUB FILE IN BLOBSTORE
		FileService fileService = FileServiceFactory.getFileService();
		AppEngineFile file = null;
		// Create a new Blob file with mime-type "text/plain"
		try {
			file = fileService.createNewBlobFile("application/epub+zip", Title+ ".epub");
			// Open the channel to write to it
			boolean lock = true;
			FileWriteChannel writeChannel = fileService.openWriteChannel(file,lock);

			OutputStream out = Channels.newOutputStream(writeChannel);
			Epub epub = new Epub(Title, Chap, ContentOfChap);
			OCFContainerWriter writer = new OCFContainerWriter(out);
			epub.epub.serialize(writer);
			out.close();

			// Now finalize
			writeChannel.closeFinally();
			BlobKey blobKey = fileService.getBlobKey(file);
			String blobkey = blobKey.getKeyString();
			
			return blobkey;
		} catch (Exception e) {
			e.printStackTrace();
			return "Exception in creating BLOB file : " + e;

		}
	}

	private String escapeHtml(String html) {
		if (html == null)
			return null;
		
		return html.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
	}
}
